
#import
# Register your models here.
from django.contrib import admin
from django import forms
from .models import Device_info,Device_attribute,Device_maintenance_log,Device_lable,Loginlog,doc,Alex_day_maintenance,Alex_mouth_maintenance
from .models import organ_index_company,organ_index_scene,organ_index_class,organ_index_project,consumable_materials,Enter_times,maintenance_times
from .models import electricity_meter,Temperature_humidity
from .widgets import *
from django.utils.safestring import mark_safe
from django.utils.html import format_html
from django.forms import ModelForm
from serverworker.funqrcode.qr_lable import create_lable
from django.http import HttpResponse
from openpyxl import Workbook
import matrix.confs.conf_network as conf
import io
from jsoneditor.forms import JSONEditor
from django.urls import reverse
#from daterange_filter.filter import DateRangeFilter
#setting
admin.site.site_header='matrix'
admin.site.site_title='matrix'
admin.site.index_title='matrix'


#标记功能
def make_unavailable(modeladmin, request, queryset):
    queryset.update(available=False)  # 将选中的产品标记为无货
make_unavailable.short_description = "标记为无货"


class ProductForm(forms.ModelForm):
    class Meta:
        model = Device_info
        fields = '__all__'
        widgets = {
            'stock': forms.Textarea(attrs={'rows': 3, 'cols': 10}),
        }
class Device_infoAdmin(admin.ModelAdmin):
    def copy_one(self, obj):

        return format_html(f"""
                            <input type="text" id="{obj.id}" value="{obj.code_label}" style="position: absolute; top: -10000px">
                            <a href="#" onclick="document.getElementById('{obj.id}').select(); document.execCommand('copy')">复制</a>
                            """
                         )
    copy_one.type = 'success'
    copy_one.short_description = '复制标签'

    #点击跳转 not
    def on_link(self, obj):
        a='点击'
        return format_html(f"""
                            <input type="text" id="{obj.id}" value="{obj.code_label}" style="position: absolute; top: -10000px">
                            <a href="#" onclick="document.getElementById('{obj.id}').select(); document.execCommand('copy'); alert('跳转开发中...')">{a}</a>
                            """
                         )
        #<a href="#" onclick="document.getElementById('{obj.id}').select(); document.execCommand('copy'); alert('跳转开发中...')">{a}</a>
        #document.execCommand('insertHTML', false, '<img src=  http://127.0.0.1:8000/static/image/2.png width=100 height=100>');
    on_link.type = 'success'
    on_link.short_description = '跳转详情页'


    form = ProductForm
        #
    ''' json格式化显示
            formfield_overrides = {
                    JSONField: {'widget': PrettyJSONWidget}
            }
    '''

    # 跳转到设备详情
    def topo(self, obj):
        return mark_safe(
            f'<a href="{conf.url}admin/serverworker/device_attribute/?device_name__device_id__exact={obj.device_id}" >点击跳转</a>')
            #f'<a href="http://127.0.0.1:8000/admin/serverworker/device_attribute/?device_name={obj.device_name+obj.device_id}" target="_blank">点击跳转</a>'
            #target="_blank" 新开页面


    topo.short_description = '设备详情'
    topo.allow_tags = True

    list_display = ("company","scene","project","device_class","device_name","device_id","admin_user","teach_user","watch_user","create_user",'func','topo',"create_time",)
        # 自定义显示的列
    search_fields = ('device_name','device_id')
        # 添加搜索功能
    list_filter = ('company','scene','project',"device_class")
        # 添加过滤功能
    #date_hierarchy = "create_time"
            #在模型列表页面中添加一个日期层次结构导航
    #actions = [make_unavailable]
    list_display_links = ('device_name',)
        # 指定在模型列表页面上点击哪个字段的链接会进入编辑页面
    #list_editable = ('company',)
            #用于在模型列表页面中允许直接编辑某些字段的值，而不必进入编辑页面
    ordering = ["company","scene","project","device_class","device_name",]
    # 设置每页显示的条数,降低性能消耗
    list_per_page = 25

#设备详情 Device_attribute
class Device_attributeAdmin(admin.ModelAdmin):

    list_display = ( 'device_name','a1','b1','c1','d1','e1','f1','g1','h1','notes_view','create_user','create_time','order_id','is_head') #
        # 自定义显示的列
    search_fields = ('device_name',)
        # 添加搜索功能
    list_filter = ('device_name',)
        # 添加过滤功能
    # date_hierarchy = "create_time"
    # 在模型列表页面中添加一个日期层次结构导航
        # actions = [make_unavailable]
    list_display_links = ('device_name',)
        # 指定在模型列表页面上点击哪个字段的链接会进入编辑页面
    #list_editable = ('func',)
        # 用于在模型列表页面中允许直接编辑某些字段的值，而不必进入编辑页面

    #readonly_fields = ('image_data',)  # 必须加这行 否则访问编辑页面会报错
    ordering = ['-is_head','order_id','create_time',]
        # 设置默认排序,-为降序
    # 设置每页显示的条数,降低性能消耗
    list_per_page = 25

    # admin后台缩略图显示
    def image_data(self, obj):
        return mark_safe(u'<img src="%s" height=50px width="50px" />' % obj.cover.url)  # cover为model中定义的cover字段
    image_data.short_description = u'封面11'


    # 备注字段-优化显示-换行
    def notes_view(self, obj):
        return format_html('<textarea cols=40 rows={} readonly>{}</textarea>', 1, obj.notes)
        #return format_html('<textarea cols=40 rows={} readonly>{}</textarea>', obj.notes.count('\n') - 3, obj.notes)
        #return format_html('<pre>{}</pre>', obj.notes)
    notes_view.short_description = u'备注'

    #not
    def color_is_head(self, obj):
        color = 'red' if obj.is_head == True else 'black'
        return format_html('<span style="color: {};">{}</span>',color, obj.is_head)
    color_is_head.allow_tags = True

#维修记录
class Device_maintenance_logAdmin(admin.ModelAdmin):
    list_display = (
    "device_name","maintenance_user","replace","problem","solution",'image_photo1',"image_photo2","image_photo3","notes_view","create_time",'plan_color',)  # "status"
    # 自定义显示的列

    list_filter = ('create_time',"device_name","maintenance_user")
    # 添加过滤功能
    # actions = [make_unavailable]
    #list_display_links = ('device_name',)
    # 指定在模型列表页面上点击哪个字段的链接会进入编辑页面
    # list_editable = ('func',)
    # 用于在模型列表页面中允许直接编辑某些字段的值，而不必进入编辑页面
    # readonly_fields = ('image_data',)  # 必须加这行 否则访问编辑页面会报错
    search_fields = ("device_id","device_name")
    # 添加搜索功能
    ordering = ['-create_time']
    # 设置默认排序为create_time字段升序

    # admin后台缩略图显示
    def image_photo1(self, obj):
        return mark_safe(u'<img src="%s" height=50px width="50px" />' % obj.photo1.url)
    image_photo1.short_description = '照片'
    def image_photo2(self, obj):
        return mark_safe(u'<img src="%s" height=50px width="50px" />' % obj.photo2.url)
    image_photo2.short_description = '照片'
    def image_photo3(self, obj):
        return mark_safe(u'<img src="%s" height=50px width="50px" />' % obj.photo3.url)
    image_photo3.short_description = '照片'


    # 备注字段-优化显示-换行
    def notes_view(self, obj):
        return format_html('<textarea  cols=40 rows={} readonly> {}</textarea>', obj.notes.count('\n') - 1, obj.notes)
        # return format_html('<textarea cols=40 rows={} readonly>{}</textarea>', obj.notes.count('\n') - 3, obj.notes)
        # return format_html('<pre>{}</pre>', obj.notes)
    notes_view.short_description = '备注'
    notes_view.color = 'red'


    def plan_color(self, obj):
        print(obj.plan)
        color = '#00cc00' if obj.plan == '维修完成' else '#ff6600'
        return format_html('<span style="color: {};">{}</span>',color, obj.plan)
    plan_color.allow_tags = True
    plan_color.short_description = '进度'

# lab 二维码
class LabelAdmin(admin.ModelAdmin):
    # 屏蔽新增按钮, 屏蔽删除按钮
    def has_add_permission(self, request):
        return False
    def has_delete_permission(self, request, obj=None):
        return False

    # 自定义单个二维码下载按钮
    def qr_download_button(self, obj):
        web = f'{conf.url}qr_download?device_id={obj.device_id}&device_name={obj.device_name}&scene={obj.scene}&project={obj.project}&device_class={obj.device_class}&func={obj.func}'
        return format_html(
            f'<a href="{web}" style="color: red; background-color: green;" class="button" > <font color="white">下载</font></a>',
            web
        )
    qr_download_button.short_description = '操作'

    # 显示图片
    def display_image(self, obj):
        lw=700//2
        lh=170//2

        #return format_html(f'<img src="http://127.0.0.1:8000/static/image/2.png" width="{lw}" height="{lh}" />')
        #return format_html(f'<a href="http://127.0.0.1:8000/qr?device_id={obj.device_id}&device_name={obj.device_name}&scene={obj.scene}&project={obj.project}&device_class={obj.device_class}&" >display_image</a>')
        return format_html(f'<img src="{conf.url}qr?device_id={obj.device_id}&device_name={obj.device_name}&scene={obj.scene}&project={obj.project}&device_class={obj.device_class}&func={obj.func}" width="{lw}" height="{lh}" />')

    #nor
    def testa(self, obj):
        return obj.device_id +obj.device_name
    display_image.short_description = '标签'
    form = ProductForm
    list_display = ("company","scene","project","device_class","device_name","device_id",'display_image',"create_time",'qr_download_button',)
        # 自定义显示的列
    search_fields = ('device_name','device_id')
        # 添加搜索功能
    list_filter = ('company','scene','project')
        # 添加过滤功能
    #date_hierarchy = "create_time"
        # 在模型列表页面中添加一个日期层次结构导航
    #actions = [make_unavailable]
    #list_display_links = ('device_name',)
        # 指定在模型列表页面上点击哪个字段的链接会进入编辑页面
    #list_editable = ('company',)
        # 用于在模型列表页面中允许直接编辑某些字段的值，而不必进入编辑页面
    #readonly_fields = ('popup_image',)
    # 设置每页显示的条数,降低性能消耗
    list_per_page = 25

#登录日志
class Loginlog_admin(admin.ModelAdmin):
    # 屏蔽新增按钮, 屏蔽删除按钮
    def has_add_permission(self, request):
        return False
    def has_delete_permission(self, request, obj=None):
        return False

    list_display = ('user','pcname','os','remot','addr','ag',"create_time")
    list_filter = ("create_time",'user',)
    readonly_fields = ('user','pcname','os','remot','addr','ua','ag','status',"create_time",)
    list_per_page = 100
    ordering = ["-create_time",'user']

#操作日志 @装饰器方式注册
@admin.register(admin.models.LogEntry)
class admin_logAdmin(admin.ModelAdmin):
    """该类用于显示 admin 内置的 django_admin_log 表。其中，content_type 是指用户修改的 Model 名"""

    # 屏蔽新增按钮, 屏蔽删除按钮
    def has_add_permission(self, request):
        return False
    def has_delete_permission(self, request, obj=None):
        return False


    list_display = ['user', 'content_type', '__str__','action_time']
    #list_display_links = ['action_time']
    list_filter = ['action_time', 'content_type', 'user']
    readonly_fields = ['action_time', 'user', 'content_type','object_id', 'object_repr', 'action_flag', 'change_message']


####################################################################报表
class enter_times_Admin(admin.ModelAdmin):
    display =['user','times','proportion']
class maintenance_times_Admin(admin.ModelAdmin):
    list_display =['user','times','proportion']
class alex_day_maintenance_Admin(admin.ModelAdmin):
    # 屏蔽新增按钮, 屏蔽删除按钮
    def has_add_permission(self, request):
        return False
    def has_delete_permission(self, request, obj=None):
        return False

    def export_as_excel(self, request, queryset):
        meta = self.model._meta
        field_names = [field.name for field in meta.fields]


        response = HttpResponse(content_type='application/msexcel')
        response['Content-Disposition'] = f'attachment; filename={meta}.xlsx'
        wb = Workbook()
        ws = wb.active
        ws.append(field_names)
        for obj in queryset:
            for field in field_names:
                data = [f'{getattr(obj, field)}' for field in field_names]
            row = ws.append(data)

        wb.save(response)
        return response
    export_as_excel.short_description = '导出表格'
    actions = ['export_as_excel']
    list_display = ('device_name','times','date',"create_time",)
    list_filter = ("date",)
    ordering = ['-date','device_name',]
    list_per_page = 25

class alex_mouth_maintenance_Admin(admin.ModelAdmin):
    pass
class consumable_materials_Admin(admin.ModelAdmin):
    pass

#文档文件，pdf在线，使用pdf.js实现
class doc_Admin(admin.ModelAdmin):

    #readonly_fields = ('notes','create_user','create_time','pdf_preview',)
    list_display = ( 'pdf_file','notes', 'create_user', 'create_time',)


    #not 读取是直接显示，不需要以下
    def pdf_preview(self, obj):

        return format_html(
            f'<iframe src="http://{conf.domain}:8000/static/pdf/web/viewer.html?file={0}" width="100%" height="600px"></iframe>',
            obj.pdf_file.url
        )
    pdf_preview.short_description = '文件'
    def embed_pdf_file(self, obj):
        if (obj.pdf_file != None and obj.pdf_file != ""):
            return mark_safe(
                '<embed src="{0}" type="application/pdf" width="50%" height="400px"/>'.format(obj.pdf_file.url, ))
    def test1(self,obj,al):
        print('hello world')
    actions = ['test1', ]
    embed_pdf_file.short_description = 'Question'

class organ_index_company_admin(admin.ModelAdmin):
    list_display = ('company', 'comp_addr', 'main_user1', 'main_user2','func','create_user','create_time',)
    ordering = ('create_time',)
class organ_index_scene_admin(admin.ModelAdmin):
    list_display = ('scene', 'func','create_user','create_time',)
    ordering = ('create_time',)
class organ_index_project_admin(admin.ModelAdmin):
    list_display = ('project','func','create_user','create_time',)
    ordering = ('create_time',)
class organ_index_class_admin(admin.ModelAdmin):
    list_display = ('device_class', 'func','create_user','create_time',)
    ordering = ('create_time',)

class electricity_meter_Admin(admin.ModelAdmin):
    list_display = ('u','i','q','w','create_time',)
    ordering = ('create_time',)
class Temperature_humidity_Admin(admin.ModelAdmin):
    list_display = ('temperature', 'humidity','create_time',)
    ordering = ('create_time',)

admin.site.register(doc, doc_Admin)
admin.site.register(Device_info,Device_infoAdmin)
admin.site.register(Device_attribute,Device_attributeAdmin)
admin.site.register(Device_maintenance_log,Device_maintenance_logAdmin)
admin.site.register(Device_lable,LabelAdmin)
admin.site.register(Loginlog,Loginlog_admin)
admin.site.register(organ_index_company,organ_index_company_admin)
admin.site.register(organ_index_scene,organ_index_scene_admin)
admin.site.register(organ_index_class,organ_index_class_admin)
admin.site.register(organ_index_project,organ_index_project_admin)
admin.site.register(Alex_day_maintenance,alex_day_maintenance_Admin)
admin.site.register(Alex_mouth_maintenance,alex_mouth_maintenance_Admin)
admin.site.register(consumable_materials,consumable_materials_Admin)
admin.site.register(Enter_times,enter_times_Admin)
admin.site.register(maintenance_times,maintenance_times_Admin)
admin.site.register(electricity_meter,electricity_meter_Admin)
admin.site.register(Temperature_humidity,Temperature_humidity_Admin)